package com.nhc.activity_fragment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.astrob.activitys.DMapActivity;
import com.astrob.model.LonLat;
import com.astrob.model.Msg;
import com.astrob.nhcmap.R;
import com.astrob.util.CoordChange;
import com.astrob.util.SysUtils;
import com.astrob.util.Utils;
import com.astrob.view.BaseViewHolder;
import com.nhc.database.dbmodel.WayPoint;
import com.nhc.database.manager.DBDataCenter;

import java.util.ArrayList;
import java.util.List;

import zuo.biao.library.base.BaseActivity;
import zuo.biao.library.base.BaseAdapter;
import zuo.biao.library.model.Entry;
import zuo.biao.library.ui.AlertDialog;
import zuo.biao.library.ui.EditTextInfoWindow;
import zuo.biao.library.ui.PageScroller;

public class SearchTypeActivity extends BaseActivity implements AlertDialog.OnDialogButtonClickListener {
    private final String TAG = "SearchTypeActivity";

    //启动方法<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    public static final String RESULT_SEARCH_ONLYSELECT = "RESULT_SEARCH_ONLYSELECT";
    public static final String RESULT_SEARCH_ASWARNING = "RESULT_SEARCH_ASWARNING";

    public static final String RESULT_SEARCH_FROMMORE = "RESULT_SEARCH_FROMMORE";
    public static final String RESULT_SEARCH_FROMNAVILINE = "RESULT_SEARCH_FROMNAVILINE";

    /**
     * 启动这个Activity的Intent
     *
     * @param context
     * @return
     */
    public static Intent createIntent(Context context, boolean onlyselect) {
        return new Intent(context, SearchTypeActivity.class)
                .putExtra(RESULT_SEARCH_ONLYSELECT, onlyselect);
    }

    public static Intent createIntent(Context context, boolean onlyselect, boolean asWarningpt) {
        return new Intent(context, SearchTypeActivity.class)
                .putExtra(RESULT_SEARCH_ONLYSELECT, onlyselect)
                .putExtra(RESULT_SEARCH_ASWARNING, asWarningpt);
    }

    public static Intent createIntentfromMore(Context context) {
        return new Intent(context, SearchTypeActivity.class)
                .putExtra(RESULT_SEARCH_FROMMORE, true);
    }

    //航线添加航点，地图方式
    public static Intent createIntentfromNaviLine(Context context) {
        return new Intent(context, SearchTypeActivity.class)
                .putExtra(RESULT_SEARCH_FROMNAVILINE, true);
    }
    //启动方法>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

    @Override
    public Activity getActivity() {
        return this;
    }

    boolean _onlyselect = false;//点选查询结果直接返回，不再onmap
    boolean _asWarningpt = false;//onmap后，添加的航点作为警告点

    boolean _frommore = false;//more菜单->查找 （显示坐标选项）

    boolean _fromnaviline = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.searchtype_activity);

        intent = getIntent();
        _onlyselect = intent.getBooleanExtra(RESULT_SEARCH_ONLYSELECT, _onlyselect);
        _asWarningpt = intent.getBooleanExtra(RESULT_SEARCH_ASWARNING, _asWarningpt);
        _frommore = intent.getBooleanExtra(RESULT_SEARCH_FROMMORE, _frommore);
        _fromnaviline = intent.getBooleanExtra(RESULT_SEARCH_FROMNAVILINE, _fromnaviline);
        //功能归类分区方法，必须调用<<<<<<<<<<
        initView();
        initData();
        initEvent();
        //功能归类分区方法，必须调用>>>>>>>>>>
    }


    //UI显示区(操作UI，但不存在数据获取或处理代码，也不存在事件监听代码)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    //示例代码<<<<<<<<
    private ListView lv_searchtype;

    //示例代码>>>>>>>>
    @Override
    public void initView() {//必须在onCreate方法内调用
        autoSetTitle();//自动设置标题为上个Activity传入的INTENT_TITLE

        //示例代码<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
        lv_searchtype = (ListView) findViewById(R.id.lv_searchtype);
        //示例代码>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

        if (_fromnaviline) {
            _onlyselect = true;
        }

    }

    //示例代码<<<<<<<<
    private DemoAdapter adapter;
    //示例代码>>>>>>>>

    /**
     * 示例方法 ：显示列表内容
     *
     * @param list
     */
    private void setList(List<Entry<Integer, String>> list) {
        if (adapter == null) {
            adapter = new DemoAdapter(context);
            lv_searchtype.setAdapter(adapter);
        }
        adapter.refresh(list);
    }
    //UI显示区(操作UI，但不存在数据获取或处理代码，也不存在事件监听代码)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>


    //Data数据区(存在数据获取或处理代码，但不存在事件监听代码)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    //示例代码<<<<<<<<
    private List<Entry<Integer, String>> searchtypelist;
    private final int[] SEARCHTYPE_IDS = {
            R.drawable.icon_point, R.drawable.icon_building, R.drawable.icon_government,
            R.drawable.icon_food, R.drawable.icon_hotel, R.drawable.icon_shopping,
            R.drawable.icon_gas, R.drawable.icon_school, R.drawable.icon_hospital,
            R.drawable.icon_traffic, R.drawable.icon_entertainment};

    private final int[] SEARCHTYPEMORE_IDS = {
            R.drawable.btn_compile_u, R.drawable.icon_point, R.drawable.icon_building, R.drawable.icon_government,
            R.drawable.icon_food, R.drawable.icon_hotel, R.drawable.icon_shopping,
            R.drawable.icon_gas, R.drawable.icon_school, R.drawable.icon_hospital,
            R.drawable.icon_traffic, R.drawable.icon_entertainment};

    private final int[] SEARCHTYPE_IDS_FROMNAVILINE = {
            R.drawable.btn_map_pressed, R.drawable.icon_point, R.drawable.icon_building, R.drawable.icon_government,
            R.drawable.icon_food, R.drawable.icon_hotel, R.drawable.icon_shopping,
            R.drawable.icon_gas, R.drawable.icon_school, R.drawable.icon_hospital,
            R.drawable.icon_traffic, R.drawable.icon_entertainment};

    //示例代码>>>>>>>>>
    @Override
    public void initData() {//必须在onCreate方法内调用
        //示例代码<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
        showProgressDialog(R.string.loading);
        runThread(TAG + "initData", new Runnable() {
            @Override
            public void run() {
                searchtypelist = getList();
                runUiThread(new Runnable() {
                    @Override
                    public void run() {
                        dismissProgressDialog();
                        setList(searchtypelist);
                    }
                });
            }
        });
        //示例代码>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    }

    protected List<Entry<Integer, String>> getList() {
        searchtypelist = new ArrayList<Entry<Integer, String>>();
        if (_frommore) {
            String[] SEARCHTYPE_NAMES = getResources().getStringArray(R.array.searchtypemore_names);
            for (int i = 0; i < SEARCHTYPE_NAMES.length; i++) {
                searchtypelist.add(new Entry<Integer, String>(i, ""));
            }
        } else if (_fromnaviline) {
            String[] SEARCHTYPE_NAMES = getResources().getStringArray(R.array.searchtypefromline_names);
            for (int i = 0; i < SEARCHTYPE_NAMES.length; i++) {
                searchtypelist.add(new Entry<Integer, String>(i, ""));
            }
        } else {
            String[] SEARCHTYPE_NAMES = getResources().getStringArray(R.array.searchtype_names);
            for (int i = 0; i < SEARCHTYPE_NAMES.length; i++) {
                searchtypelist.add(new Entry<Integer, String>(i, ""));
            }
        }
        return searchtypelist;
    }

    //Data数据区(存在数据获取或处理代码，但不存在事件监听代码)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>


    //Event事件区(只要存在事件监听代码就是)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    @Override
    public void initEvent() {//必须在onCreate方法内调用
        //示例代码<<<<<<<<<<<<<<<<<<<
        lv_searchtype.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                doSearch(position);
            }
        });

        //分页滚动示例代码<<<<<<<<<<<<<<<<<<<
        new PageScroller(lv_searchtype).init();
        //分页滚动示例代码>>>>>>>>>>>>>>>>>>>

        //示例代码>>>>>>>>>>>>>>>>>>>
    }

    private void doSearch(int typeIndex) {
        if (_frommore) {
//            查找中添加“坐标”，点击坐标可以直接输入或粘贴经纬度并直接向该点进行导航
            if (typeIndex == 0) {
                intent = EditLonLatActivity.createIntent(context, null);
                toActivity(intent, REQUEST_TO_EDIT_LONLAT_INFO);
            } else {
                toActivity(HCSearchActivity.createIntent(this, typeIndex - 1, _onlyselect, _asWarningpt), REQUEST_TO_SEARCH);
            }
        } else if (_fromnaviline) {
            if (typeIndex == 0) {
                toActivity(DMapActivity.createIntentFromAdd(context), REQUEST_TO_ONMAP);
            } else {
                toActivity(HCSearchActivity.createIntent(this, typeIndex - 1, _onlyselect, _asWarningpt), REQUEST_TO_SEARCH);
            }
        } else {
            toActivity(HCSearchActivity.createIntent(this, typeIndex, _onlyselect, _asWarningpt), REQUEST_TO_SEARCH);
        }
    }

    //系统自带监听方法<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    //@user 新增方法

    @Override
    public void finish() {
        super.finish();
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                break;
        }
        return super.onKeyUp(keyCode, event);
    }

    private final int REQUEST_TO_SEARCH = 23;
    private final int REQUEST_TO_EDIT_LONLAT_INFO = 24;
    private final int REQUEST_TO_ONMAP = 26;

    private WayPoint mWayPoint;//导航到输入的坐标点

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_TO_SEARCH) {
            if (resultCode == Msg.SEACHSELECTEDONE) {
                setResult(Msg.SEACHSELECTEDONE);
                finish();
            }
        } else if (requestCode == REQUEST_TO_ONMAP) {
            if (resultCode == Msg.SEACHSELECTEDONE) {
                setResult(Msg.SEACHSELECTEDONE);
                finish();
            }
        } else if (requestCode == REQUEST_TO_EDIT_LONLAT_INFO) {
            if (data != null) {

                LonLat ll = null;
                if (SysUtils.getInstance().coord_format > 2) {
                    String strLL = data.getStringExtra(EditTextInfoWindow.RESULT_VALUE);
//                    tvLat.setText(strLL);
                    //大地坐标->GPS坐标->火星坐标---保存
                    int coord_mode = SysUtils.getInstance().coord_mode;
                    int coord_format = SysUtils.getInstance().coord_format;
                    ll = CoordChange.getInstance().change2LL(strLL, coord_mode, coord_format);
                    ll = Utils.wgs84togcj02(ll.GetLon(), ll.GetLat());
                } else {
                    ll = (LonLat) data.getSerializableExtra(EditTextInfoWindow.RESULT_VALUE);
                    ll = Utils.wgs84togcj02(ll.GetLon(), ll.GetLat());
                }

                if (ll != null && ll.IsValid()) {
                    mWayPoint = new WayPoint();
                    mWayPoint.setName(Utils.getLLStr(ll, 2));
                    mWayPoint.setLL(ll);

                    if (DBDataCenter.getInstance().routeNavi != null) {
                        new AlertDialog(context, "", getString(R.string.qstopdest) + mWayPoint.getName() + "]？", true, 11, this).show();
                    } else if (DBDataCenter.getInstance().wayTrailNavi != null) {
                        new AlertDialog(context, "", getString(R.string.qstopdest_line) + mWayPoint.getName() + "]？", true, 11, this).show();
                    } else {

                        DBDataCenter.getInstance().routeNavi = null;
                        DBDataCenter.getInstance().wayTrailNavi = null;

                        DBDataCenter.getInstance().makerNavi = mWayPoint;
                        setResult(Msg.NAVI_TO_DEST);
                        finish();
                    }
                }

            }
        }

        if (resultCode != RESULT_OK) {
            return;
        }
//        switch (requestCode) {
//            case REQUEST_TO_BOTTOM_MENU:
//                if (data != null) {
//                    onBottomMenuItemClick(data.getIntExtra(BottomMenuWindow.RESULT_ITEM_ID, -1));
//                }
//                break;
//            case REQUEST_TO_EDIT_TEXT_INFO:
//                if (user == null) {
//                    user = new User(userId);
//                }
//                user.setTag(data == null ? null : data.getStringExtra(EditTextInfoActivity.RESULT_VALUE));
//                setUser(user);
//                break;
//        }
    }


    //系统自带监听方法>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    //Event事件区(只要存在事件监听代码就是)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>


    //Adapter
    public class DemoAdapter extends BaseAdapter<Entry<Integer, String>> {
        public DemoAdapter(Activity context) {
            super(context);
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = LayoutInflater.from(context).inflate(
                        R.layout.icontext_view, parent, false);
            }

            TextView tv_name = BaseViewHolder.get(convertView, R.id.tv_name);
            ImageView iv_icon = BaseViewHolder.get(convertView, R.id.iv_icon);

            final Entry<Integer, String> kvb = getItem(position);
            int index = kvb.getKey();
            int max = SEARCHTYPE_IDS.length;
            int StringArrayID = R.array.searchtype_names;
            if (_frommore) {
                max = SEARCHTYPEMORE_IDS.length;
                StringArrayID = R.array.searchtypemore_names;
            } else if (_fromnaviline) {
                max = SEARCHTYPE_IDS_FROMNAVILINE.length;
                StringArrayID = R.array.searchtypefromline_names;
            }
            if (index < 0 || index >= max) {
                index = 0;
            }
            String[] SEARCHTYPE_NAMES = getResources().getStringArray(StringArrayID);
            tv_name.setText(SEARCHTYPE_NAMES[index]);
            if (_frommore) {
                iv_icon.setImageResource(SEARCHTYPEMORE_IDS[index]);
            } else if (_fromnaviline) {
                iv_icon.setImageResource(SEARCHTYPE_IDS_FROMNAVILINE[index]);
            } else {
                iv_icon.setImageResource(SEARCHTYPE_IDS[index]);
            }

            return super.getView(position, convertView, parent);
        }

        private final long serialVersionUID = 3L;

        @Override
        public long getItemId(int position) {
//            return getItem(position).getId();
            return serialVersionUID + position;
        }
    }

    @Override
    public void onDialogButtonClick(int requestCode, boolean isPositive) {
        if (isPositive == false) {
            return;
        }

        if (requestCode == 11) {
            DBDataCenter.getInstance().routeNavi = null;
            DBDataCenter.getInstance().wayTrailNavi = null;
            DBDataCenter.getInstance().makerNavi = mWayPoint;
            setResult(Msg.NAVI_TO_DEST);
            finish();
        }
    }


}